///第三方体系 子公司 合同产品选择新增的  反写到 三方体系总公司的合同产品中
public with sharing class ContractProductSystemController {

	public string  resJson {get;set;}//选中的结果的json 

	public string  cpListJson {get;set;}//可供选择的合同产品json

	public string  conId {get;set;}//要反写的合同的ID

	public string  tableTitle {get;set;}//表头

	public string  parentconId ;//总公司的id

	public Set<Id> productSet ;//总公司当年的有效合同产品

	public string company ;///公司

	public string msg {get;set;}//前后台交互信息

	public Boolean isSuccess {get;set;}//是否保存成功

    public ContractProductSystemController() {
        conId = System.currentPageReference().getParameters().get('conId');
        productSet= new Set<Id>();
       	cpListJson = '[]';

    }
    public void init (){

    	System.debug( '==='+conId);
    	///合同和合同对应的三方分支机构的总公司
    	Contract__c con = [select Id,Account__r.ParentId,CompanyControls__c from Contract__c where Id=:conId];
    	
    	company = con.CompanyControls__c;
    	///获取总公司当下的年度合同
    	Contract__c parentcon = [select Id from Contract__c where Account__c =:con.Account__r.ParentId and Year__c =:String.valueOf(System.now().year()) and Status__c ='已生效' order by createdDate desc limit 1];

    	
    	if(parentcon != null){
    		parentconId = parentcon.Id;
    		for (ContractProduct__c cp: [select Id,Product__c from ContractProduct__c where Contract__c =: parentconId]) {
    			productSet.add(cp.Product__c);
    		}

    		///获取合同产品
            cpListJson = this.getCPList(conId);
            System.debug( cpListJson);
    		
    	}	

    	

    }
    public String getCPList(String cid){
    	List<ContractProductBean> cpList = new List<ContractProductBean>();
    	for (ContractProduct__c cp : [select Id,SalesPrice__c,Product__c,Product__r.Name,Product__r.SerialNo__c,Product__r.Spec__c ,DiscountRate__c,Product__r.Category1__c
    		from ContractProduct__c where Contract__c =:cid]) {
    	 	if(!productSet.contains(cp.Product__c))cpList.add(new ContractProductBean(cp));
    	} 

    	return  EncodingUtil.urlEncode(JSON.serialize(cpList), 'UTF-8');
    	
    }
    public void saveres (){
    	msg ='';
       Savepoint sp = Database.setSavepoint();
       try {
       	System.debug(resJson);
	          List<Object> os = (List<Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(resJson,'UTF-8')) ;
	                 	System.debug(os);

	    	List<ContractProduct__c> resList = new List<ContractProduct__c>();
	    	 Id rt  = Utils.getRecordTypeIdByDevNameAndObjName('ContractCommodityProduct','ContractProduct__c');                                   

	    	 Set<Id> pids = new Set<Id>();
                         System.debug('ANY o'+productSet);

	    	for ( Object o : os) {


	    	 	  Map<String ,Object> res = (Map<String ,Object> )o ;
                  if(res.get('productId') == null)continue;
	    	 	  if(!productSet.contains(Id.valueOf(String.valueOf(res.get('productId'))))){
	    	 	  	pids.add(Id.valueOf(String.valueOf(res.get('productId'))) );
	    	 	  }else{
	    	 	  	msg += '<p>'+res.get('productName')+'--'+res.get('spec')+'--'+res.get('serialNo')+'</p>';
	    	 	  }
	    	 	  

	    	 } 
             System.debug('ANY o'+msg);
	    	 if(msg.length() > 0){
	    	 	 msg = '<h2>分支机构对应的总公司当下年度合同已经存在下列合同产品:</h2>' + msg;
	    	 	 isSuccess = false;
	    	 	return;
	    	 }
	    	 Map<Id,Price__c> priceMap = getPriceMap(pids);
	    	 List<ContractProduct__c> insertList = new List<ContractProduct__c>();
	    	for (Object o : os) {
                

	    		Map<String ,Object> res = (Map<String ,Object> )o ;
                if(res.get('productId') == null)continue;
	    		Id productId = Id.valueOf(String.valueOf(res.get('productId')));
	    		ContractProduct__c cp = new ContractProduct__c();
	    		cp.Contract__c = parentconId;
	    		cp.Name = String.valueOf(res.get('productName'));
	            cp.Product__c = productId;
	            cp.AreaDealerPrice__c = priceMap.containsKey(productId) ? priceMap.get(productId).AreaDealerPrice__c : null;
	            cp.InvoiceDealerPrice__c = priceMap.containsKey(productId) ? priceMap.get(productId).InvoiceDealerPrice__c : null;
	      		cp.UnitPrice1__c = priceMap.containsKey(productId) ? priceMap.get(productId).MarketPrice__c : null;//市场报价
	      		cp.SalesPrice__c = Decimal.valueOf(String.valueOf(res.get('salesprice'))) ;
	            cp.Taxrate__c =priceMap.containsKey(productId) ? priceMap.get(productId).Taxrate__c : null ;
	            cp.ProductLine__c = String.valueOf(res.get('category1')) ;
	            cp.RecordTypeId = rt;
	            cp.DiscountRate__c =  Decimal.valueOf(String.valueOf(res.get('discountrate'))) ;
	            cp.DelContractProduct__c = false;
	            cp.IsSycToNc__c = false;
	    		// cp.Product__c = o.get()
	    		insertList.add(cp);

	    	} 
                         System.debug('ANY o'+insertList);

	    	if(insertList.size() > 0)insert insertList;
	    	isSuccess = true;
       }catch (Exception e) {
       		msg = '保存失败:'+e.getMessage();
           	Database.rollback(sp);
            System.debug('==='+msg);
           isSuccess = false;

       }     
    	

    }
     private  Map<Id,Price__c> getPriceMap(Set<Id> pids){
      Map<Id, Price__c> priceMap = new Map<Id, Price__c>();
            for (Price__c pr : [select Id, Product__c,Product__r.bggsjhdj__c, MarketPrice__c, HospitalManagerPrice__c, HospitalBottomPrice__c, CompanyBottomPrice__c,
                AreaDealerPrice__c, InvoiceDealerPrice__c, RepairCost__c, InstCost__c ,LastMonthAveragePrice__c,Taxrate__c  
                                from Price__c where Product__c in : pids and Company__c =:company]) {
                priceMap.put(pr.Product__c, pr);
            }
      return priceMap;
  
  }
    public class ContractProductBean{
    	public string  cpId ;///合同产品id
    	public string  productId ;
    	public string  productName ;
    	public string  spec ;
    	public string  serialNo ;
    	public Decimal  salesprice ;
    	public Boolean  chk ;
    	public string   category1;
    	public Decimal discountrate;
    	public ContractProductBean(ContractProduct__c cp){
    		cpId = cp.Id;
    		productName = cp.Product__r.Name ;
    		productId = cp.Product__c;
    		spec = cp.Product__r.Spec__c;
    		serialNo = cp.Product__r.SerialNo__c;
    		salesprice = cp.SalesPrice__c;
    		category1 = cp.Product__r.Category1__c;
    		discountrate = cp.DiscountRate__c;
    		chk = false;
    	}

    }

    
}